package com.pj.compose.ui.compose

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.pj.compose.R

import com.pj.compose.model.TextIconEntity
import com.pj.compose.ui.theme.c999999
import com.pj.compose.ui.theme.cEAEDEE

@Composable
fun MainGridView(items: List<TextIconEntity>, onItemClick: (Int) -> Unit) {
    LazyVerticalGrid(
        columns = GridCells.Fixed(3),
        modifier = Modifier
            .background(cEAEDEE)
            .padding(top = 1.dp, bottom = 1.dp),
        horizontalArrangement = Arrangement.spacedBy(1.dp),
        verticalArrangement = Arrangement.spacedBy(1.dp)
    ) {
        items.forEachIndexed { index, it ->
            item {
                MainGridItemView(entity = it) {
                    onItemClick(index)
                }
            }
        }
    }
}

@Composable
fun MainGridItemView(entity: TextIconEntity, onClick: () -> Unit) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.White)
            .padding(vertical = 15.dp)
            .clickable(onClick = onClick),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Image(
            painter = painterResource(id = entity.iconId),
            contentDescription = "icon",
            modifier = Modifier
                .width(60.dp),
            contentScale = ContentScale.FillWidth
        )
        Text(
            text = entity.label,
            modifier = Modifier.padding(top = 5.dp),
            color = c999999,
            maxLines = 1
        )
    }
}

@Preview
@Composable
fun MainGridPreview() {
    MainGridView(
        items = listOf(
            TextIconEntity("第一页", R.drawable.ic_tab_app),
            TextIconEntity("第二页", R.drawable.ic_tab_app),
            TextIconEntity("第三页", R.drawable.ic_tab_app),
            TextIconEntity("第四页", R.drawable.ic_tab_app),
            TextIconEntity("第五页", R.drawable.ic_tab_app),
            TextIconEntity("第六页", R.drawable.ic_tab_app),
        )
    ) {}
}